package com.manager.managersystem.config.security.filter;

import com.manager.managersystem.config.redis.RedisService;
import com.manager.managersystem.config.security.exception.CustomerAuthenticationException;
import com.manager.managersystem.config.security.handler.LoginFailureHandler;
import com.manager.managersystem.config.security.service.CustomerUserDetailsService;
import com.manager.managersystem.util.JwtUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author mao
 * @date 2023/5/5
 * @apiNoto
 */

@Data
@Component
public class CheckTokenFilter extends OncePerRequestFilter {

    //登录请求地址
    @Value("${request.login.url}")
    private String loginUrl;

    @Resource
    private RedisService redisService;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private CustomerUserDetailsService customerUserDetailsService;

    @Resource
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            //获取当前请求url地址
            String url = request.getRequestURI();
            //判断当前请求是否是登录请求,如果不是登录请求,则需要进行token验证
            if (!url.contains(loginUrl)) {
                //进行token验证
                this.validateToken(request);
            }
        } catch (AuthenticationException e) {
            // 如果出现异常,则进行异常处理
            loginFailureHandler.onAuthenticationFailure(request, response, e);
        }
        //登录请求不须要携带token,可以直接放行
        doFilter(request,response,filterChain);
    }

    /**
     * 验证token信息
     * @param request
     */
    private void validateToken(HttpServletRequest request){
        //获取前端请求提交的token信息
        //先从header里面找
        String token = request.getHeader("token");
        //如果token问空,则从请求参数总获取token
        if (ObjectUtils.isEmpty(token)) {
            token = request.getParameter("token");
        }
        //如果请求参数中也没有token则抛出异常
        if (ObjectUtils.isEmpty(token)) {
            throw new CustomerAuthenticationException("Token不存在");
        }
        //判断Redis中有没有token
        String tokenKey = "token_" + token;
        String redisToken = redisService.get(tokenKey);
        //判断redis中是否存在token信息,如果为空,则表示token失效
        if (ObjectUtils.isEmpty(redisToken)) {
            throw new CustomerAuthenticationException("Token失效,已过期");
        }
        //如果请求带来的token与redis不一致,则验证失败
        if (!token.equals(redisToken)) {
            throw new CustomerAuthenticationException("Token验证失败");
        }
        //如果token存在,则解析出用户名
        String username = jwtUtils.getUsernameFromToken(token);
        //判断用户名是否为空
        if (ObjectUtils.isEmpty(username)) {
            throw new CustomerAuthenticationException("token解析失败");
        }
        //获取用户信息
        UserDetails userDetails = customerUserDetailsService.loadUserByUsername(username);
        //判断用户信息是否为空
        if (ObjectUtils.isEmpty(userDetails)) {
            throw new CustomerAuthenticationException("Token验证失败");
        }
        //创建用户身份信息对象
        UsernamePasswordAuthenticationToken authentication = new
                UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        //设置请求的信息
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        //将认证的信息交给SpringSecurity上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);

    }
}
